import VueRouter from 'vue-router'

import About from '../pages/About'
import Home from '../pages/Home'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'

const router = new VueRouter({
  routes: [
    {
      name: 'aboutMe', // 命名路由
      path: '/about',
      component: About,
      meta: { title: '关于' },
    },
    {
      name: 'main',
      path: '/home',
      component: Home,
      meta: { title: '主页' },
      children: [
        {
          path: 'news', // 不带/
          component: News,
          meta: { isAuth: true, title: '新闻' },
          children: [
            {
              name: 'info2',
              path: 'detail',
              component: Detail,
              // props写法3: props值为函数，该函数返回的对象中每一组key-value都会通过props传给Detail组件
              props(route) {
                return {
                  id: route.query.id,
                  title: route.query.title,
                }
              },
            },
          ],
        },
        {
          path: 'message',
          component: Message,
          meta: { isAuth: true, title: '消息' },
          children: [
            {
              name: 'info',
              path: 'detail/:id/:title', // 使用占位符接受params参数
              component: Detail,
              // props写法1: 值为对象,该对象中所有的key-value的组合最终都会通过props传给Detail组件
              // props:{a:1, b:'hello'},
              // props写法2: 值为布尔值，布尔值为true，则把路由收到的所有params参数通过props传给Detail组件
              props: true,
            },
          ],
        },
      ],
    },
  ],
})

//全局前置守卫：初始化时/被切换前 调用
router.beforeEach((to, from, next) => {
  console.log('beforeEach', to, from)
  if (to.meta.isAuth) {
    //判断当前路由是否需要进行权限控制
    if (localStorage.getItem('school') === 'zjut') {
      //权限控制的具体规则
      next() //放行
    } else {
      alert('暂无权限查看，去localStorage里加个school:zjut')
      // next({name:'guanyu'})
    }
  } else {
    next() //放行
  }
})

//全局后置守卫：初始化时/路由切换后执行
router.afterEach((to, from) => {
  console.log('afterEach', to, from)
  if (to.meta.title) {
    document.title = to.meta.title //修改网页的title
  } else {
    document.title = 'vue_demo'
  }
})

export default router
